import { find, ScrollView, Vec3 } from 'cc';
import { JsonAsset } from 'cc';
import { resources } from 'cc';
import { EventTouch } from 'cc';
import { error } from 'cc';
import { sys } from 'cc';
import { _decorator, Component, Node, Label, view, UITransform } from 'cc';
import { App } from '../App';
import { localKey } from '../common/Common';
import CommConst from '../const/CommConst';
import wsTool from '../net/ws';
import UtilTool from '../tools/UtilTool';
import ScrollHelper from './ScrollHelper';
const { ccclass, property } = _decorator;

// 系统公告界面
@ccclass('NoticePanel') 
export class NoticePanel extends Component {
    @property(Node)
    contentNode: Node = null;

    @property(Node)
    scroll1: Node = null;

    @property(Node)
    scroll2: Node = null;

    @property(Node)
    emptyNode: Node = null;

    @property(Node)
    detailsNode: Node = null;

    @property(Node)
    detailsMes: Node = null;

    private itemNum = 6
    // [listData]列表数据  [isLoading]是否加载中 [loadOver]是否加载结束(如果没有新的数据则认为是加载结束) [currPage]当前已经请求的第几页的数据 [dataDirty]是否需要重新拉取数据 
    // 记录数据
    private configData = {listData : [], isLoading : false, loadOver : false, currPage : 0, dataDirty : true, pageSize : 30}
    private noticeData = null

    private HallObj = null

    onLoad() {
        UtilTool.setScreen(this.node)
        UtilTool.nodeActive(this.contentNode,5)
    }

    start() {
        this.node.getComponent(UITransform).setContentSize(view.getVisibleSize())
        this.emptyNode.active = true
        this.detailsNode.active = false

        this.reqData()
    }

    initData(obj){
        this.HallObj = obj
    }

    /**
     * 请求数据
     */
    reqData(pInit=true) {
        this.configData.isLoading = true
        
        wsTool.send({"msgCode":CommConst.Req_SYSTEM_NOTICE, "page":this.configData.currPage, "pageSize":this.configData.pageSize,"languageId":App.language.languageId_default.toString()})
        .then(res =>{
            // if (res?.result == 0) {
                // 数据回来
                // let res = {list:[]}
                this.noticeData= res
                this.configData.currPage = this.configData.currPage + 1
                this.configData.isLoading = false
                /* res.list = [{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e51","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e52","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0egfdhfgjfgjjfghdjdghfjghdjhygkjhuyoiuphgjdhgdjgh52000","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e53","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e54","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e55","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e56","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e57","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102}]   // 测试数据 */
                res.list.forEach(element => {
                    this.configData.listData.push(element)
                });
                if (res.list==null || res.list.length < this.configData.pageSize) {
                    this.configData.loadOver = true
                }

                this.emptyNode.active = this.configData.listData.length<=0?true:false

                // 最新请求的数据列表大于0，才会去刷新界面
                if (res.list.length>0) {
                    let param = {
                        init:pInit, 
                        data:this.configData.listData, 
                        itemNum:this.itemNum, 
                        itemFun: (obj,idx,objIdx)=>{
                            this.refreshItem(obj,idx,objIdx)
                        },
                        endFun:()=>{
                            this.OnScrollEnd()
                        }
                    }
    
                    this.scroll1.getComponent(ScrollHelper).setData(param)
                }
                 
                
            // }
            // else{
            //     alert('获取数据失败')
            // } 
        })
    }

    /** 
     * 刷新数据
     * param obj item对象
     * param idx 实际的下标索引
     * param objIdx item本身的下标索引
    */
    refreshItem(obj,idx,objIdx) {
        if (this.configData.listData.length <= 0) {
            return
        }

        let title = find("di/title", obj).getComponent(Label)   // 标题
        let time = find("di/time", obj).getComponent(Label)   // 时间
        let mes = find("di/mes", obj).getComponent(Label) // 内容
        let redPoint = find("di/redPoint", obj)    // 红点

        let itemData = this.configData.listData[idx]
        title.string = itemData.title
        time.string = UtilTool.formatTimeStamp(itemData.startTime)

        // itemData.content = "HHHHHHHHHHFFFFFFFFFfGGGGGGGGGGDDDDDDDDDDLLLLLLLLLLHHHHHHHHHHLLLLLLLLLL"
        // itemData.content = "阿斯蒂芬第三方但施工方给对方给对方和广泛地好复工后发给规范化规范化风格和规范化超高层发第三方士大夫"
        mes.string = UtilTool.subUTF8Str(itemData.content,70) 

        // 点击详情
        let detailsBtn = find("di", obj)
        detailsBtn.off(Node.EventType.TOUCH_END)
        detailsBtn.on(Node.EventType.TOUCH_END,(event: EventTouch) =>{
            this.showDetails(idx)
        },detailsBtn)

        redPoint.active = !this.isReadNotice(itemData.id)
        
    }

    // 滚动视图滑到底部回调
    OnScrollEnd() {
        if (this.configData.isLoading) {
            return
        }
        if (this.configData.loadOver) {
            return
        }

        this.reqData(false)
    }

    /** 
     * 显示公告详情
      */
    showDetails(idx) {
        App.Audio.playOneShot("click")

        // UtilTool.nodeActive(this.detailsNode, 5)
        this.detailsNode.active = true

        let itemData = this.configData.listData[idx]
        this.detailsMes.getComponent(Label).string = itemData.content
        this.detailsMes.scale = new Vec3(0,0,0)

        // 标题
        find("bg2/title",this.detailsNode).getComponent(Label).string = itemData.title
        setTimeout(() => {
            this.detailsMes.scale = new Vec3(1,1,1)
            let H = this.detailsMes.getComponent(UITransform).height
            let content = this.scroll2.getComponent(ScrollView).content
            if (H > 1200) {
                content.getComponent(UITransform).setContentSize(content.getComponent(UITransform).contentSize.width, H)
            }
            else {
                content.getComponent(UITransform).setContentSize(content.getComponent(UITransform).contentSize.width, 1200)
                H = 1200
            }

            this.detailsMes.setPosition(-380,H)
            this.scroll2.getComponent(ScrollView).scrollToTop()
        }, 100);

        this.saveNotice(itemData.id)
        
        /* resources.load('noticeId', (err: any, res: JsonAsset) => {
            if (err) {
                error(err.message || err);
                return;
            }
            // 获取到 Json 数据
            let jsonData: object = res.json;
            UtilTool.printLog("jsonData",jsonData)
        }) */
    }

    /** 
     * 是否是已读公告
      */
    isReadNotice(id) {
        let noticeId =  App.Util.getLocalItem(localKey.NOTICE_ID, "")
        noticeId = noticeId + ""
        let idArr = noticeId.split(",")
        let isRead = idArr.indexOf(id.toString())!=-1
        return isRead
    }

    /** 
     * 保存已读公告
      */
    saveNotice(id) {
        let noticeId =  App.Util.getLocalItem(localKey.NOTICE_ID, "")
        noticeId = noticeId + ""
        let idArr = noticeId.split(",")
        if (idArr.length<=1 && idArr=="") {
            noticeId = id + ""
            App.Util.setLocalItem(localKey.NOTICE_ID, noticeId)
        }
        else {
            if (idArr.indexOf(id.toString()) == -1) {
                noticeId = noticeId + "," + id
                App.Util.setLocalItem(localKey.NOTICE_ID, noticeId)
            }
        }
    }

    /** 
     * 关闭详情
      */
    clickCloseDetails() {
        App.Audio.playOneShot("click")
        this.detailsNode.active = false
    }

    /** 
     * 关闭
      */
    clickClose() {
        App.Audio.playOneShot("click")

        if (this.HallObj){
            this.HallObj.reqNoticeIDList()
        }
        
        this.node.destroy();
    }
    
}

